﻿using Futuret.Core.Futuret.Interface;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace Future.Shared.Core.Registrar;

/// <summary>
///     Author: Riva
///     Date: 2023/7/11 14:14
///     Description:
/// </summary>
public abstract partial class AbstractApiDependencyRegistrar : IMiddlewareRegistrar
{
    /// <summary>
    ///     构造函数
    /// </summary>
    /// <param name="app"></param>
    protected AbstractApiDependencyRegistrar(IApplicationBuilder app)
    {
        _app = app;
    }

    /// <summary>
    ///     IApplicationBuilder
    /// </summary>
    protected IApplicationBuilder _app { get; init; } = default!;

    /// <summary>
    ///     注册中间件入口方法
    /// </summary>
    public abstract void UseAdd();

    /// <summary>
    ///     注册webapi通用中间件
    /// </summary>
    protected virtual void UseWebApiDefault()
    {
        var environment = _app.ApplicationServices.GetRequiredService<IHostEnvironment>();

        _app.UseRouting();

        if (!environment.IsProduction())
        {
            // 在开发环境中，使用异常页面，这样可以暴露错误堆栈信息，所以不要放在生产环境。
            _app.UseDeveloperExceptionPage();
            //开发环境启动swaggerUi
            _app.UseSwagger();
            _app.UseSwaggerUI();
        }

        _app.UseCors("cors");

        _app.UseHttpsRedirection();

        // 先开启认证
        _app.UseAuthentication();
        // 然后是授权中间件
        _app.UseAuthorization();

        _app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
    }
}